import 'dart:convert';
import 'package:dio/dio.dart';
import '../utils/toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter/material.dart';
import '../provider/index.dart';
import 'package:provider/provider.dart';

class Http {
  var dio;
  var context;
  Http(this.context);
  dioInit() {
    dio = Dio(
      BaseOptions(
        baseUrl: "http://sc.rulaiyun.cn/api/index.php/v1",
        connectTimeout: 5000,
        receiveTimeout: 100000,
        headers: {
          "Authorization":
              'Bearer ' + Provider.of<GlobalData>(context, listen: false).token,
        },
      ),
    );
    dio.interceptors
        .add(InterceptorsWrapper(onResponse: (Response response) async {
      var resData = jsonDecode(response.toString());
      EasyLoading.dismiss();
      if (resData['code'] == 200) {
        return resData;
      } else if (resData['code'] > 4000 && resData['code'] < 5000) {
        Navigator.of(context).pushReplacementNamed('/login');
        showToast(resData['msg']);
      } else {
        showToast(resData['msg']);
      }
      return response;
    }, onError: (DioError e) async {
      // 当请求失败时做一些预处理
      EasyLoading.dismiss();
      showToast('网络错误!');
      print('eeeeeeeeeeeeeeeeee${e}');
      return e; //continue
    }));
  }

  loading() {
    EasyLoading.instance..userInteractions = false;
    EasyLoading.show(status: '加载中...');
  }

  getHttp(url, data, {bool tug = false}) async {
    dioInit();
    if (!tug) loading();
    try {
      Response response = await dio.get(url, queryParameters: data);
      return response;
    } catch (e) {
      return e;
    }
  }

  postHttp(url, data, {bool tug = false}) async {
    dioInit();
    if (!tug) loading();
    try {
      Response response = await dio.post(url, data: data);
      return jsonDecode(response.toString());
    } catch (e) {
      return e;
    }
  }
}
